using System;
using TinyServerLib;
using System.Net;
using System.IO;

using TinyLogger;

namespace DtGoogleServer
{
	/// <summary>
	/// Summary description for GoogleServer.
	/// </summary>
	public class GoogleServer : TinyServer
	{
		public GoogleServer()
		{			
		}
		protected override void doGet(string argument)
		{
			getGoogle(argument);
		}


		private void getGoogle(string url)
		{			
			HttpWebRequest req;
            string localURL = "http://www.google.com" + removeTrailers(url);
			try 
			{
				this.logger.AddLog( LogLevel.Informational, "Google URL: '{0}'", localURL);
				req = WebRequest.Create(localURL) as HttpWebRequest;
				req.UserAgent="User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)";
			}
			catch(System.UriFormatException uriEx)
			{
				Console.WriteLine("Error in request: {0}", uriEx.Message);
				return;
			}
			WebResponse resp;
			try
			{
				resp = req.GetResponse();
			} 
			catch (System.Net.WebException wex)
			{
				Console.WriteLine ("Error in response: {0}", wex.Message);
				return;
			}
			Stream str = resp.GetResponseStream();
			int realLen = 0;
			int len = 1024*1024;
			Byte [] buf = new Byte[(int)(len+1)];
			do 
			{
				realLen= str.Read(buf, 0, len);
				if (realLen > 0)
					this.sendBytes(buf, realLen);
			} while (realLen > 0);
		}

		private string removeTrailers(string cmd)
		{
			if (cmd.IndexOf(" ") > 0)
			{ 
				int idx = cmd.LastIndexOf("HTTP");
				return 
					cmd.Substring(0, idx).TrimEnd();
			}
			else
				return cmd;
		}
	}
}
